package cn.edu.sdjzu.xg11.web;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import cn.edu.sdjzu.xg11.domain.Teacher;
import cn.edu.sdjzu.xg11.service.DegreeService;
import cn.edu.sdjzu.xg11.service.DepartmentService;
import cn.edu.sdjzu.xg11.service.TeacherService;
import cn.edu.sdjzu.xg11.service.TitleService;

@Controller
@RequestMapping("/teacher")
//将名为"teacher"的对象存入Session中
//否则updateTeacher.jsp中被修改的teacher无法传递到update方法中。
@SessionAttributes("teacher")
public class TeacherController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger
			.getLogger(TeacherController.class);

	@Autowired
	private TeacherService teacherService;
	@Autowired
	private DegreeService degreeService;
	@Autowired
	private TitleService titleService;
	@Autowired
	private DepartmentService departmentService;
	@Autowired
	
			
	// RequestMappingr的value属性可以省略"html"
	//本方法的@RequestMapping的路径相对于类定义 @RequestMapping("/teacher")
	@RequestMapping("/listTeachers")
	public ModelAndView list() {
		System.out.println(teacherService.getTeachers());
		// 创建MV对象，第1参数为逻辑视图名称，加上bysj-servlet.xml中指定的前缀和后缀
		// 第2参数为模型名称，视图中可以通过该参数读取第3参数
		// 第3参数为模型数据
		ModelAndView mv = new ModelAndView("/teacher/listTeachers",
				"teachers",
				teacherService.getTeachers());
		return mv;
	}

	// 使用{id}作为url中的占位符
	@RequestMapping(value = "/deleteTeacher/{id}", method = RequestMethod.GET)
	// @pathVariable将url中的参数设置为方法参数
	public ModelAndView delete(@PathVariable("id") String id) {
		Integer id_i = new Integer(id);
		teacherService.deleteTeacher(id_i);
		// 刷新
		ModelAndView returnModelAndView = this.list();
		return returnModelAndView;
	}

	@RequestMapping(value = "/toAddTeacher")
	public ModelAndView toAddTeacher(){
		ModelAndView mv = new ModelAndView("/teacher/addTeacher");
		mv.addObject("teacher", new Teacher());
		prepareObjects(mv);
		return mv;
	}
	
	@RequestMapping(value = "/addTeacher", method = RequestMethod.POST)	
	public ModelAndView add(@Valid Teacher teacher,
			BindingResult bindingResult,
			HttpServletRequest request) {
		if(bindingResult.hasErrors()){
			System.out.println(teacher.getName().length());
			System.out.println("********  error对象 开始********");
			System.out.println(bindingResult);
			System.out.println("********  error对象 结束********");
			ModelAndView mv = new ModelAndView("/teacher/addTeacher");
			prepareObjects(mv);
			return mv;
		}		
		teacherService.addTeacher(teacher);
		//如果不使用redirect的话，当前的地址仍然为"/bysj/teacher/addTeacher.html"。
		//如果刷新的话，会重新调用本方法，从而重复地增加一个设计题目 ！！！
//		return this.list().getViewName();转发模式，目标地址不变
		return new ModelAndView("redirect:/teacher/listTeachers.html");//重向模式
	}
	
	// 使用{id}作为url中的占位符
	@RequestMapping(value = "/updateTeacher/{id}", method = RequestMethod.GET)
	// @pathVariable将url中的参数设置为方法参数
	public ModelAndView toUpdate(@PathVariable("id") String id,HttpServletRequest request) {
		if (logger.isDebugEnabled()) {
			logger.debug("toUpdate(String, HttpServletRequest) - start");
		}

		Integer id_i = new Integer(id);
		ModelAndView mv = new ModelAndView("/teacher/updateTeacher",
				"teacher",
				teacherService.getTeacher(id_i));
		prepareObjects(mv);

		if (logger.isDebugEnabled()) {
			logger.debug("toUpdate(String, HttpServletRequest) - end");
		}
		return mv;
	}
	
	@RequestMapping(value = "/updateTeacher", method = RequestMethod.POST)	
	public String update(Teacher teacher,SessionStatus status) {
		if (logger.isDebugEnabled()) {
			logger.debug("update(Teacher, SessionStatus) - start");
		}

		teacherService.updateTeacher(teacher);
		//将teacher从session中清除掉
		status.setComplete();
		if (logger.isDebugEnabled()) {
			logger.debug("update(Teacher, SessionStatus) - end");
		}
		//如果不使用redirect的话，当前的地址仍然为"/bysj/teacher/updateTeacher.html"。
		//如果刷新的话，会重新调用本方法，而status.setComplete清除了session，所以会出现
		//"Session attribute 'teacher' required - not found in session"		
//		return this.list().getViewName();转发模式，目标地址不变
		return "redirect:/teacher/listTeachers.html";//重向模式
								  
	}

	private void prepareObjects(ModelAndView mv) {
		if (logger.isDebugEnabled()) {
			logger.debug("prepareObjects(ModelAndView) - start");
		}

		mv.addObject("degrees", degreeService.getDegrees());
		mv.addObject("titles", titleService.getTitles());		
		mv.addObject("department",departmentService.getDepartments());

		if (logger.isDebugEnabled()) {
			logger.debug("prepareObjects(ModelAndView) - end");
		}
	}
//	/teacher/teacherToExcel.html
	@RequestMapping("/teacherToExcel.html")
	public String toExcel(Model mm){
		mm.addAttribute("teacherList",
				teacherService.getTeachers());
		return "teacherListExcel";///bysj-servlet.xml中的<!-- Excel视图配置 -->bean
	}
	
}
